/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */
import type { MaProTableColumns, MaProTableExpose } from "@mineadmin/pro-table";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import defaultAvatar from "@/assets/images/defaultAvatar.jpg";
import { ElTag, ElImage } from "element-plus";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import hasAuth from "@/utils/permission/hasAuth.ts";
import { deleteByIds } from "$/attractions/commerce/api/commerceCommodity.ts";
import { page as commodityTypePage } from "$/attractions/commerce/api/commerceCommodityType.ts";
import { page as merchantPage } from "$/attractions/commerce/api/commerceMerchant.ts";

export default function getTableColumns(
  dialog: UseDialogExpose,
  formRef: any,
  t: any
): MaProTableColumns[] {
  const msg = useMessage();

  const commodityTypeList = ref<any[]>([]);
  const merchantList = ref<any[]>([]);

  onMounted(async () => {
    const res = await commodityTypePage({
      page: 1,
      pageSize: 1000,
    });
    if (res.code === 200 && res.data && res.data.list) {
      commodityTypeList.value = res.data.list;
    }

    const res2 = await merchantPage({
      page: 1,
      pageSize: 1000,
    });
    if (res2.code === 200 && res2.data && res2.data.list) {
      merchantList.value = res2.data.list;
    }
  });

  return [
    {
      type: "selection",
      showOverflowTooltip: false,
      label: () => t("crud.selection"),
    },
    { label: "商品名称", prop: "commodity_name" },
    {
      label: "商品类型",
      prop: "commodity_category",
      cellRender: ({ row }) => {
        const commodityTypeName = commodityTypeList.value.find(
          (commodityType) => commodityType.id === row.commodity_category
        );
        return commodityTypeName?.name || `商户类型${row.commodity_category}`;
      },
    },
    { label: "商品品牌", prop: "commodity_brand" },
    { label: "商品型号", prop: "commodity_model" },
    {
      label: "商户名称",
      prop: "merchant_id",
      cellRender: ({ row }) => {
        const merchantName = merchantList.value.find(
          (merchant) => merchant.id === row.merchant_id
        );
        return merchantName?.merchant_name || `商户名称${row.merchant_id}`;
      },
    },
    { label: "计量单位", prop: "commodity_unit" },
    { label: "销售价", prop: "sale_price" },
    { label: "折扣", prop: "discount" },
    { label: "满减金额", prop: "full_amount" },
    { label: "满减额度", prop: "full_reduction" },
    { label: "库存数量", prop: "stock_quantity" },
    {
      label: "商品图片",
      prop: "commodity_images",
      cellRender: ({ row }) => {
        if (!row.commodity_images) {
          return h("span", { style: { color: "#999" } }, "暂无图片");
        }

        // 获取API基础URL
        const env = import.meta.env;
        const baseUrl =
          env.VITE_OPEN_PROXY === "true"
            ? env.VITE_PROXY_PREFIX
            : env.VITE_APP_API_BASEURL;
        const imageUrl = `${baseUrl}${row.commodity_images}`;

        return h(
          ElImage,
          {
            src: imageUrl,
            alt: "商品图片",
            style: {
              width: "60px",
              height: "40px",
              borderRadius: "4px",
              border: "1px solid #ddd",
            },
            fit: "cover",
            previewSrcList: [imageUrl],
            previewTeleported: true,
            onError: () => {
              console.warn("商品图片加载失败:", imageUrl);
            },
          },
          {
            error: () =>
              h(
                "div",
                {
                  style: {
                    width: "60px",
                    height: "40px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    backgroundColor: "#f5f5f5",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    fontSize: "12px",
                    color: "#999",
                  },
                },
                "加载失败"
              ),
          }
        );
      },
    },
    {
      type: "operation",
      label: () => t("crud.operation"),
      operationConfigure: {
        actions: [
          {
            name: "edit",
            icon: "material-symbols:person-edit",
            show: ({ row }) =>
              hasAuth("commerce_commodity:commerceCommodity:update"),
            text: () => t("crud.edit"),
            onClick: ({ row }) => {
              dialog.setTitle(t("crud.edit"));
              dialog.open({ formType: "edit", data: row });
            },
          },
          {
            name: "del",
            icon: "mdi:delete",
            text: () => t("crud.delete"),
            show: ({ row }) =>
              hasAuth("commerce_commodity:commerceCommodity:delete"),
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm(t("crud.delDataMessage")).then(async () => {
                const response = await deleteByIds([row.id]);
                if (response.code === ResultCode.SUCCESS) {
                  msg.success(t("crud.delSuccess"));
                  proxy.refresh();
                }
              });
            },
          },
        ],
      },
    },
  ];
}
